package com.refusea.train.utils

import org.jsoup.Jsoup
import org.jsoup.safety.Safelist


object HtmlSanitizer {

    private const val HOST = "https://static.refusea.com"

    private val allowedTags = arrayOf(
        "h1", "h2", "h3", "h4", "h5", "h6",
        "b", "strong", "i", "em", "u",
        "ul", "ol", "li",
        "p", "div",
        "img",
        "br",
    )

    private val allowedAttributes = listOf(
        "img" to arrayOf("src", "alt"),
        "p" to arrayOf("class")
    )

    private val safes = Safelist().apply {
        this.addTags(*allowedTags)
        allowedAttributes.forEach { (tag, attributes) ->
            this.addAttributes(tag, *attributes)
        }
    }

    fun check(html: String): Boolean {
        return Jsoup.isValid(html, safes) &&
                Jsoup.parseBodyFragment(html).select("img").all {
                    it.attr("src").startsWith(HOST)
                }
    }
}
